
(function(window,document){
    const rootElement = document.compatMode=="CSS1Compat"?document.documentElement:document.body;
    const appHeader = document.getElementById("app-header");
    const waitingElement = document.getElementById("waiting");
    const appElement = document.getElementById("app");
    const loginElement = document.getElementById("login-form");
    const loginBtn = document.getElementById("login-btn");
    
    const workarea = document.getElementById("workarea");
    const nav = document.getElementById("nav");
    const chats = document.getElementById("chats");
    const chatlist = document.getElementById("chat-list");
    const search = document.getElementById("search");

    

    let chatApp=window.chatApp={};
    let isWaiting=false;
    chatApp.waiting=function(txt){
        let centerWaiting = function(){
            waitingElement.style.top = (rootElement.clientHeight - waitingElement.clientHeight)/2;
            waitingElement.style.left = (rootElement.clientWidth - waitingElement.clientWidth)/2;
        };
        if(txt!==false){
            waitingElement.style.display="block";
            chatApp.showMain(false);
            chatApp.login(false);
            loginElement.style.display = "none";    
            if(txt===true || txt===undefined || txt===null) txt="";
            waitingElement.lastElementChild.innerHTML = txt;
            centerWaiting();
            if(!isWaiting)window.addEventListener("resize",centerWaiting);
            isWaiting = true;
        }else {
            waitingElement.style.display="none";
            if(isWaiting) window.removeEventListener("resize",centerWaiting);
            isWaiting = false;
        }
        return this;
    }

    let isLoginShow =false;
    chatApp.login=function(onSubmit){
        let centerLogin = function(){
            loginElement.style.top = (rootElement.clientHeight - loginElement.clientHeight)/2;
            loginElement.style.left = (rootElement.clientWidth - loginElement.clientWidth)/2;
        };

        if(onSubmit===false){
            loginElement.style.display="none";
            if(isLoginShow) window.removeEventListener("resize",centerLogin);
            isLoginShow = false;
        }else{
            loginElement.style.display="block";
            chatApp.showMain(false);chatApp.waiting(false);
            
            centerLogin();
            if(!isLoginShow) window.addEventListener("resize",centerLogin);
            isLoginShow = true;
            if(typeof onSubmit==="function") loginBtn.onclick = onSubmit;
        }
    }
    let isMainShow;
    chatApp.showMain = function(onSend){
        let adjustSizes = function(){
            const currChat = document.getElementById("current-chat");
            const currChatCaption = document.getElementById("current-chat-caption");
            const messages = document.getElementById("messages");
            const opElement = document.getElementById("op");
            let h = rootElement.clientHeight-2;
            chats.style.height = currChat.style.height = nav.style.height = h + "px";
            chatlist.style.height = h-search.clientHeight- appHeader.clientHeight + "px";
            messages.style.height = h- currChatCaption.clientHeight - opElement.clientHeight - appHeader.clientHeight + "px";
        };
        if(onSend!==false){
            appElement.style.display = "block";
            chatApp.waiting(false);chatApp.login(false);
            if(!isMainShow) window.addEventListener("resize",adjustSizes);
            adjustSizes();
            if(typeof onSend==="function"){
                document.getElementById("send-btn").onclick = onSend;
            }
            isMainShow = true;
        }else{
            appElement.style.display ="none";
            if(isMainShow) window.removeListener("resize",adjustSizes);
            isMainShow = false;
        }
    }
    chatApp.attechWindowEvents=function(opts){

    }

    
class HttpRequest extends Promise<any>{
    xhr:XMLHttpRequest;
    method:"GET"|"POST"|"PUT"|"DELETE"|"OPTIONS"|"HEADER";
    url:string;
    headers:{[name:string]:string|[]};
    async:boolean;
    data:any;
    type:""|"json"|"url-encoding"|"blob";
    responseType?:"" | "arraybuffer" | "blob" | "document" | "json" | "text" | "xml"|"response";

    constructor(public opts:IHttpRequestOpts){
        super((resolve,reject)=>{
            let xhr = this.xhr;//new XMLHttpRequest
            xhr.open(this.method,this.url,this.opts.async!==false);
            let responseType = this.responseType;
            xhr.responseType = responseType==="xml"?"":(responseType==="response"?"":responseType);
            let reqHeaders = this.headers;
            xhr.onreadystatechange = ()=> {
            //准备状态改变触发
                if(xhr.readyState == 4) {
                    if(xhr.status !== 200) {
                        reject("http error:"+xhr.status);
                        return ;
                    }else{
                        let result;
                        try{
                            result = new HttpResponse(xhr,this);
                        }catch(ex) {
                            return reject(ex);
                        }
                        resolve(result.data);
                    }

                }
            }
            xhr.onerror = reject;
        });
        
    }
    static optsToken:string = "AJAX_OPTS";
}
YA.defineSingleonProperty(HttpRequest.prototype,{
    "method":(self:HttpRequest)=>self.opts.method?self.opts.method.toUpperCase():"GET"
    ,"type":(self:HttpRequest)=>self.opts.type|| "url-encoding"
    ,"url":(self:HttpRequest)=>{
        let url = self.opts.url;
        if(url===undefined) url = window.location.href;
        let method = self.method;
        if(method==="GET" || method==="DELETE" || method==="OPTIONS"){
            if(url.indexOf("?")<0){ url += "?"; url += this.data;}
            else {
                url+="&" + this.data;
            }
            if(self.opts.nocache!==false) url +="&__="+Math.random();
        }
        return url;
    }
    ,"data":(self:HttpRequest)=>{
        let data = self.opts.data;
        let type = self.type;
        if(type==="blob")return data===undefined?null:data;
        let t = typeof data;
        if(type==="json"){
            if(t==="string") return data;
            else return JSON.stringify(data);
        }else {
            let str = "";
            if(t==="object"){
                for(const n in data){
                    if(str) str+= "&";
                    str += encodeURIComponent(n);
                    str +="=";
                    str += encodeURIComponent(data[n]);
                }
                return str;
            }
            return data===null||data===undefined?"":data.toString();
        }
    }
    ,"xhr":(self)=>{
        var xhr = null;
        if(window.XMLHttpRequest){//判断当前浏览器是否支持XMLHttpRequest
            xhr = new XMLHttpRequest();
        }else if(window.XMLHttpRequest){//判断当前浏览器是否支持XMLHttpRequest，这是对于IE浏览器的判断
            try{
                xhr = new ActiveXObject("Msxml2.XMLHTTP");//IE6及以后的版本支持的
            }catch(e){
                try{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');//IE6以下版本的支持
                }catch(e){}
            }
        }
        return xhr;
    }
    ,"headers":(self:HttpRequest)=>{
        let optsHeaders = self.opts.headers;
        let headers = {};
        for(let n in optsHeaders){
            let value = optsHeaders[n] as string;
            headers[n]=value;
            self.xhr.setRequestHeader(n,value);
        }
        return headers;
    }
    ,"responseType":(self:HttpRequest)=>self.opts.responseType||"text"
});
export class HttpResponse{
    data:any;
    status:number;
    constructor(public xhr:XMLHttpRequest,public request:HttpRequest){
        this.status = xhr.status;
        if(this.status!==200){
            
        }
        let responseType = request.responseType;
        if(responseType==="json"){
            this.data = JSON.parse(xhr.responseText);
        }else if(responseType==="blob"||responseType=="arraybuffer"){
            this.data = xhr.response;
        }else if(responseType==="xml"){
            this.data = xhr.responseXML;
        }else if(responseType==="response"){
            this.data = this;
        } else if(responseType) this.data = xhr.responseText;
    }
    header(name:string):string|null{
        return this.xhr.getResponseHeader(name);
    }
}


    chatApp.waiting("启动中...");
})(window,document);


